<template>
  <div>
    <a-card style="margin-top: 12px;">
      <div>
        <a-form-model layout="horizontal" :model="form" ref="queryForm" :labelCol="{span: 7}" :wrapperCol="{span: 17, offset: 0}">
          <div class="fold">
            <a-row>
              <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <a-form-model-item
                  label="分组名称"
                  prop="name"
                >
                  <a-input v-model="form.name" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row type="flex" justify="end">
              <a-button @click="submitForm" type="primary">查询</a-button>
              <a-button @click="resetForm" style="margin-left: 8px">重置</a-button>
            </a-row>
          </div>
        </a-form-model>
      </div>
    </a-card>
    <a-card style="margin-top: 12px;">
      <a-row>
        <a-col :xxl="4" :lg="4" :class="[isFold ? 'animation fold-tree': 'animation', isFold ? '' : 'padding-right-12']">
          <a-spin :spinning="treeLoading">
            <div style="min-height: 600px;overflow-y: auto;overflow-x: hidden;">
              <a-tree
                :show-icon="true"
                :show-line="false"
                :tree-data="organizationTreeData"
                :expandedKeys.sync="expandedKeys"
                @select="onClickTreeNode"
              >
                <template slot="title" slot-scope="item">
                  <span v-if="item.type == 0"><a-icon type="bank" /> {{item.customTitle}} </span>
                  <span v-else-if="item.type == 1"><a-icon type="shop" /> {{item.customTitle}} </span>
                  <span v-else-if="item.type == 2"><a-icon type="apartment" /> {{item.customTitle}} </span>
                  <span v-else><a-icon type="question-circle" /> {{item.customTitle}} </span>
                </template>
              </a-tree>
            </div>
          </a-spin>
        </a-col>
        <a-col :xxl="20" :lg="20" :class="isFold ? 'animation fold-table': 'animation'">
          <div>
            <div>
              <a-button class="space-vertical" @click="foldAction">{{isFold ? `展开` : `折叠`}}</a-button>
              <a-button class="space-vertical" @click="showAddModal" type="primary" v-auth="`device:group:add`">新增</a-button>
            </div>
            <standard-table
              ref="table"
              :size="`middle`"
              :bordered="false"
              :striped="false"
              :isPagination="false"
              :loading="loading"
              :columns="columns"
              :dataSource="dataSource"
              :expandedRowKeys="expandedRowKeys"
              :onExpand="onExpand"
            >
            <div slot="action" slot-scope="{text, record}">
              <a @click="showQueryModal(record.id)" v-auth="`device:group:query`">
                查看
              </a>
              <a-divider class="row-btn-divider" type="vertical" v-auth="`device:group:edit`"/>
              <a @click="showEditModal(record.id)" v-auth="`device:group:edit`">
                编辑
              </a>
              <a-divider class="row-btn-divider" type="vertical" v-auth="`device:group:delete`"/>
              <a @click="showDeleteModal(record.id)" v-auth="`device:group:delete`">
                删除
              </a>
            </div>
          </standard-table>
        </div>
      </a-col>
    </a-row>
    <add-modal
      ref="addModal"
      :visible="visibleAddModal"
      @cancel="hideAddModal"
      @ok="addSuccess"
    />
   <edit-modal
      ref="editModal"
      :visible="visibleEditModal"
      @cancel="hideEditModal"
      @ok="editSuccess"
    />
    <query-modal
      ref="queryModal"
      :visible="visibleQueryModal"
      @cancel="hideQueryModal"
    />
    </a-card>
  </div>
</template>

<script>
import StandardTable from '@/components/table/standard-table'
import AddModal from './add-modal'
import EditModal from './edit-modal'
import QueryModal from './query-modal'
import {groupService} from '@/services'

const columns = [
  {
    title: '分组名称',
    dataIndex: 'name',
    width: 160,
    ellipsis: true
  },
  {
    title: '所属机构',
    dataIndex: 'organizationName',
    width: 150
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 100
  },
  // {
  //   title: '创建时间',
  //   dataIndex: 'createTime',
  //   width: 160
  // },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 160
  },
  {
    title: '操作',
    width: 220,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Group',
  components: { StandardTable, AddModal, EditModal, QueryModal },
  data () {
    return {
      isFold: false,
      loading: false,
      confirmLoading: false,
      treeLoading: false,
      columns: columns,
      dataSource: [],
      selectedRows: [],
      expandedRowKeys: [],
      total: 0,
      form: {
        name: undefined,
        organizationId: undefined
      },
      visibleAddModal: false,
      visibleEditModal: false,
      visibleQueryModal: false,
      organizationTreeData: [],
      expandedKeys: []
    }
  },
  authorize: {
    showQueryModal: 'device:group:query',
    showAddModal: 'device:group:add',
    showEditModal: 'device:group:edit',
    showDeleteModal: 'device:group:delete'
  },
  methods: {
    onExpand(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id);
      }
      else {
        this.expandedRowKeys = this.expandedRowKeys.filter(key => key != record.id)
      }
    },
    foldAction() {
      this.isFold = !this.isFold
    },
    reloadTable() {
      this.selectedRows = []
      this.queryListAction()
    },
    resetForm() {
      this.$refs.queryForm.resetFields()
      this.reloadTable()
    },
    submitForm() {
      this.reloadTable()
    },
    showAddModal() {
      this.visibleAddModal = true
      this.$refs.addModal.queryOrganizationTreeAction(this.form.organizationId)
      this.$refs.addModal.queryParentAction(this.form.organizationId)
    },
    showEditModal(key) {
      this.visibleEditModal = true
      this.$refs.editModal.queryAction(key)
    },
    showQueryModal(key) {
      this.visibleQueryModal = true
      this.$refs.queryModal.queryAction(key)
    },
    hideAddModal() {
      this.visibleAddModal = false
      this.$refs.addModal.$refs.form.resetFields()
    },
    hideEditModal() {
      this.visibleEditModal = false
      this.$refs.editModal.$refs.form.resetFields()
    },
    hideQueryModal() {
      this.visibleQueryModal = false
      this.$refs.queryModal.$refs.form.resetFields()
    },
    addSuccess() {
      this.hideAddModal()
      this.reloadTable()
    },
    editSuccess() {
      this.hideEditModal()
      this.reloadTable()
    },
    deleteAction(keys) {
      this.confirmLoading = true
      const params = {
        ids: keys
      }
      return groupService.del(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.$message.success(result.msg)
          this.selectedRows = []
          this.reloadTable()
        }
      }).finally(this.confirmLoading = false)
    },
    showDeleteModal (key) {
      this.$confirm({
        confirmLoading: this.confirmLoading,
        icon: 'info-circle',
        title: '警告',
        content: '你确定要删除此项吗？',
        okType: 'danger',
        onOk:() => {
          this.deleteAction([key])
        },
        onCancel() {},
      })
    },
    onPageChange(pagination) {
      this.page = pagination.current
      this.pageSize = pagination.pageSize
      this.queryListAction()
    },
    onClickTreeNode(selectedKeys) {
      this.form.organizationId = selectedKeys[0]
      this.reloadTable()
    },
    queryListAction() {
      this.loading = true
      const params = {
        page: this.page,
        pageSize: this.pageSize,
        queryParams: this.form
      }
      groupService.queryList(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.dataSource = []
          this.dataSource = result.data.records
          this.total = result.data.totalCount
          if (this.total > 0 && result.data.expRecords && result.data.records) {
            this.expandedRowKeys = result.data.expRecords
            this.dataSource = result.data.records
          }
        }
      }).finally(this.loading = false)
    },
    queryOrganizationAction() {
      this.treeLoading = true
      groupService.queryOrganizationTree().then(res => {
        const result = res.data
        if (result.code === 200) {
          this.organizationTreeData = result.data
          this.expandedKeys = []
          this.expandAllTreeNode(this.organizationTreeData, this.expandedKeys)
        }
      }).finally(this.treeLoading = false)
    },
    expandAllTreeNode(originData, targetData) {
      originData.forEach(item => {
        targetData.push(item.key)
        if (item.children && item.children.length > 0) {
          this.expandAllTreeNode(item.children, targetData)
        }
      })
    }
  },
  created() {
    this.queryOrganizationAction()
    this.reloadTable()
  }
}
</script>
<style scoped lang="less">
  .ant-form-item {
    margin-bottom: 12px;
  }
  .fold{
    width: calc(100% - 12px);
    display: inline-block
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
  .animation {
    transition: 0.5s;-webkit-transition: 0.5s;
  }
  .fold-tree {
    width: 0%;
  }
  .fold-table {
    width: 100%;
  }
</style>